export function hsva(h, s, v, a) {
  if (s > 1 || v > 1 || a > 1) {
    return;
  }
  const th = h % 360;
  const i = Math.floor(th / 60);
  const f = th / 60 - i;
  const m = v * (1 - s);
  const n = v * (1 - s * f);
  const k = v * (1 - s * (1 - f));
  const color = new Array();
  if (!s > 0 && !s < 0) {
    color.push(v, v, v, a);
  } else {
    const r = new Array(v, n, m, m, k, v);
    const g = new Array(k, v, v, n, m, m);
    const b = new Array(m, m, k, v, v, n);
    color.push(r[i], g[i], b[i], a);
  }
  return color;
}

export function torus(row, column, irad, orad) {
  const pos = [], col = [], idx = [];
  for (let i = 0; i <= row; i++) {
    let r = Math.PI * 2 / row * i;
    const rr = Math.cos(r);
    const ry = Math.sin(r);
    for (let ii = 0; ii <= column; ii++) {
      const tr = Math.PI * 2 / column * ii;
      const tx = (rr * irad + orad) * Math.cos(tr);
      const ty = ry * irad;
      const tz = (rr * irad + orad) * Math.sin(tr);
      pos.push(tx, ty, tz);
      const tc = hsva(360 / column * ii, 1, 1, 1);
      col.push(tc[0], tc[1], tc[2], tc[3]);
    }
  }
  for (let i = 0; i < row; i++) {
    for (let ii = 0; ii < column; ii++) {
      let r = (column + 1) * i + ii;
      idx.push(r, r + column + 1, r + 1);
      idx.push(r + column + 1, r + column + 2, r + 1);
    }
  }
  // return [pos, col, idx];
  let points = [];
  while (pos.length > 0) {
    let point = pos.splice(0, 3);
    points.push(point);
  }
  let triangles = [];
  while (idx.length > 0) {
    let triangle = idx.splice(0, 3);
    triangles.push(triangle);
  }
  let colors = [];
  while (col.length > 0) {
    let color = col.splice(0, 4);
    colors.push(color);
  }
  return {
    points,
    triangles,
    colors,
  };
}

let n = 16

export let torusData = torus(n, n, 1.0, 2.0);
